package com.wz.leetcode.string;

public class MultiplyStrings_43 {


    public static String multiply(String num1, String num2) {
        if (num1.equals("0") || num2.equals("0")) {
            return "0";
        }
        //   012
        // x 012
        // c x 10^i x d x 10^j = c x d x 10^(i+j)，代表后面有i + j 个0，也即
        // 所以对于逆序来讲，0位 x 0位，c x d，是要看这个乘积的进位，有进位才能在第0位
        // 这里 0 到 m + n - 1可能都有值
        // m - 1 + n - 1 = m + n - 2，所以真实情况就是 i * j -> i + j + 1位
        int[] res = new int[num1.length() + num2.length()];
        for (int i = num1.length() - 1; i >= 0; i--) {
            int n1 = num1.charAt(i) - '0';
            for (int j = num2.length() - 1; j >= 0; j--) {
                int n2 = num2.charAt(j) - '0';
                int sum = (res[i + j + 1] + n1 * n2);
                res[i + j + 1] = sum % 10;
                System.out.println("res[" + (i+j+1) + "]=" + res[i + j + 1]);
                res[i + j] += sum / 10;
            }
        }

        StringBuilder result = new StringBuilder();
        for (int i = 0; i < res.length; i++) {
            if (i == 0 && res[i] == 0) continue;
            result.append(res[i]);
        }
        return result.toString();
    }


    public static void main(String[] args) {
        String result = multiply("15", "15");
        System.out.println("result: " + result);
        System.out.println("==================================");

        String result1 = multiply("999", "999");
        System.out.println("result1: " + result1);
    }
}
